package com.fiewolf.lol.handlers;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.fiewolf.lol.entities.User;
import com.fiewolf.lol.service.IUserService;
/***
 * 用户处理器
 * @author lx
 *
 */
@Controller
@RequestMapping("/user")
public class UserHandler {
	
	@Autowired
	private IUserService uService;
	
	/**
	 	去用户登录页面
	 */
	@RequestMapping(value="/login",method=RequestMethod.GET)
	public String toLogin(Model model){//登录失败重新回到登录页面
		model.addAttribute("user", new User());
		return "login";
	}
	
	/**
	 * 登录
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/login",method=RequestMethod.POST)
	public String login(User user,Model model,HttpSession session){//登录失败重新回到登录页面
		//验证登录
		boolean verify = uService.isUserExist(user);
		if(verify){
			//登录成功后看身份
			//如果是root
			session.setAttribute("curUser", user);
			return "root_home";
			//普通用户
		}else{
			model.addAttribute("user", user);
			return "login";
		}
		
	}
	
	/**
	 * 到注册页面
	 * @return
	 */
	@RequestMapping(value="/reg",method=RequestMethod.GET)
	public String toReg(Model model){
		model.addAttribute("user", new User());
		return "reg";
	}
	
	/**
	 * 注册用户
	 * @param user
	 * @param errors
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/reg",method=RequestMethod.POST)
	public String reg(User user,Errors errors, Model model){
		//如果用户名已经存在，返回一个错误，
		//验证用户名是否唯一
		
		boolean verify = uService.isUserExist(user);
		if(!verify){
			uService.saveUser(user);//保存用户
			user.setPwd(null);
			model.addAttribute("user", user);
			return "login";
		}else{
			model.addAttribute("user", user);
			return "reg";
		}
		
	}
}
